{% extends 'index.html' %}
{% block ace-content %}
<!-- ACE Editor -->   
<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<link href="/static/dist/css/bootstrap-multiselect.css" rel="stylesheet">
<script src="/static/dist/js/bootstrap-multiselect.js"></script>
<script type="text/javascript" src="/static/dist/js/bootstrap-notify.js"></script>
<style type="text/css">
	#compile-editor {
		/* position: absolute; */
	width: 100%;
	height: 400px;
   }	
</style>
{% endblock %}
{% block page-content %}
<div id="page-wrapper">
    <div class="row">
         <div class="col-lg-12">
              <h1 class="page-header"><i class="fa  fa-wrench"></i><code>Ansible Playbook</code>配置中心</h1>
         </div>
                <!-- /.col-lg-12 -->
    </div>
	<div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
 						<i class="fa  fa-edit"></i> 修改剧本
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-lg-6">
                                <legend><i class="fa  fa-paper-plane"></i>Ansible服务器</legend>
                                    <form role="form" method="post" enctype="multipart/form-data">  {% csrf_token %}
                                        <div class="form-group">
                                            <label>剧本名称</label>
                                            <input class="form-control" name="playbook_name" value={{playbook.playbook_name}} required>
                                            <p class="help-block">例如：系统初始化</p>
                                        </div>
                                        <div class="form-group">
                                            <label>描述<i class="fa fa-info-circle" data-toggle="tooltip"  title="功能描述"></i></label>
                                            <textarea class="form-control" rows="3" id="playbook_desc" name="playbook_desc">{{playbook.playbook_desc|default:""}}</textarea>
                                            <p class="help-block">例如：用于初始化系统内核参数，关闭不必要的服务</p>
                                        </div>                                         
                                        {% if playbook.playbook_type == 1 and playbook.playbook_contents %}
                                        <div class="form-group">         
	                                        <label>剧本内容<i class="fa fa-info-circle" data-toggle="tooltip"  title="输入yaml格式数据"></i></label>                                                                
											<div id="compile-editor" class="ace_editor">{{playbook.playbook_contents}}</div> 
										</div>                                       
                                        {% endif %}
                                        <button type="reset" class="btn btn-default">撤销</button>
                                        {% if playbook.playbook_type == 1 %}
                                        <button type="button" class="btn btn-default" onclick="oBtAnsiblePlaybookOnline(this)">修改</button>
                                        {% else %}
                                        <button type="submit" class="btn btn-default">修改</button>
                                        {% endif %}
                                    
                                </div>
                                <!-- /.col-lg-6 (nested) -->
                                <div class="col-lg-6">
                                    <legend><i class="fa  fa-paper-plane-o"></i>目标服务器<i class="fa fa-info-circle" data-toggle="tooltip"  title="如果不配置，则所有人都能使用"></i></legend>
                                     <div class="form-group">
                                            <label>动态主机<i class="fa fa-info-circle" data-toggle="tooltip"  title="根据不同场景选择服务器"></i></label>
												<select class="form-control" name="server_model" id="server_model" onchange="javascript:oBtAnsibleServerl();">
													<option name="server_model" value="" >请选择一个类型</option>
													{% if playbook.playbook_server_model == 'service'  %}
														<option value="service" selected="selected" name="server_model">产品线</option>
														<option value="inventory" name="server_model">动态主机组</option>														
														<option value="group" name="server_model">使用部门</option>
														<option value="custom" name="server_model">自定义</option>
													{% elif playbook.playbook_server_model == 'group' %}
														<option value="service" name="server_model">产品线</option>
														<option value="inventory" name="server_model">动态主机组</option>
														<option value="group" selected="selected" name="server_model">使用部门</option>
														<option value="custom" name="server_model">自定义</option> 	
													{% elif playbook.playbook_server_model == 'custom' %}
														<option value="service" name="server_model">产品线</option>
														<option value="inventory" name="server_model">动态主机组</option>
														<option value="group" name="server_model">使用部门</option>
														<option value="custom" selected="selected" name="server_model">自定义</option> 		
													{% elif playbook.playbook_server_model == 'inventory' %}
														<option value="service" name="server_model">产品线类型</option>
														<option value="inventory" name="server_model" selected="selected">动态主机组</option>
														<option value="group" name="server_model">使用部门</option>
														<option value="custom" name="server_model">自定义</option>																
													{% else %}
														<option value="service" name="server_model">产品线</option>
														<option value="inventory" name="server_model">动态主机组</option>
														<option value="group" name="server_model">使用部门</option>
														<option value="custom" name="server_model">自定义</option> 																												
													{% endif %}
												</select>
                                        </div> 
										<div id='project_server'  {% if playbook.playbook_server_model != 'service'  %}style="display:none;"{% endif %}>
											<div class="form-group">
												 <label>所属产品线</label>
		                                            <select class="form-control" name="ansible_project"  id="ansible_project" onchange="javascript:oBtProjectSelect();">
		                                            	<option name="project" value="" selected="selected">请选择一个项目</option>
		                                            	{% for ds in projectList %}
		                                            		{% if ds.id == project.id %}
		                                            			<option name="project" value="{{ds.id}}" selected="selected">{{ds.project_name}}</option>
		                                            		{% else %}
		                                            			<option name="project" value="{{ds.id}}">{{ds.project_name}}</option>
		                                            		{% endif %}
		                                            	{% endfor %}
		                                            </select>
											</div>										
											<div class="form-group">
												 <label>业务类型</label>
		                                         <select class="form-control" name="ansible_service"  id="ansible_service">
		                                            	<option name="service" value="">选择一个业务类型</option>
			                                         {% for ds in serviceList %}
			                                         	{% if playbook.playbook_server_value == ds.id %}
			                                         		<option name="service" value="{{ds.id}}" selected="selected">{{ds.service_name}}</option>
			                                         	{% else %}
			                                            	<option name="service" value="{{ds.id}}">{{ds.service_name}}</option>
			                                            {% endif %}
			                                         {% endfor %}		                                            	
		                                         </select>
		                                         
											</div>	
										</div>                                        

                                        	<div id="group_server" class="form-group" {% if playbook.playbook_server_model != 'group'  %}style="display:none;"{% endif %}>
                                            <label>服务器使用组<i class="fa fa-info-circle" data-toggle="tooltip"  title="根据服务器分配的用户组选择服务器"></i></label>
		                                       <select class="form-control" name="ansible_group">
		                                           	{% for ds in groupList %}
		                                           		{% if playbook.playbook_server_value == ds.id %}
		                                           			<option name="group" selected="selected" value="{{ds.id}}">{{ds.name}}</option>
		                                           		{% else %}
		                                            		<option name="group" value="{{ds.id}}">{{ds.name}}</option>
		                                            	{% endif %}
		                                           {% endfor %}
		                                      </select>
                                        </div>  
                                        	<div id="inventory_server" class="form-group" {% if playbook.playbook_server_model != 'inventory'  %}style="display:none;"{% endif %}>
                                            <label>服务器使用组<i class="fa fa-info-circle" data-toggle="tooltip"  title="根据动态资产添加选择服务器"></i></label>
		                                       <select class="form-control" name="ansible_inventory" id="ansible_inventory" onchange="javascript:oBtInventorySelect(this);">
		                                           	{% for ds in inventoryList %}
		                                           		{% if playbook.playbook_server_value == ds.id %}
		                                           			<option name="inventory" selected="selected" value="{{ds.id}}">{{ds.name}}</option>
		                                           		{% else %}
		                                            		<option name="inventory" value="{{ds.id}}">{{ds.name}}</option>
		                                            	{% endif %}
		                                           {% endfor %}
		                                      </select>
                                        </div>                                                                               
                                        	<div id="custom_server" class="form-group" {% if playbook.playbook_server_model != 'custom'  %}style="display:none;"{% endif %}>                                       
                                            <label>勾选目标服务器<i class="fa fa-info-circle" data-toggle="tooltip"  title="自定选择服务器"></i></label>
                                            <select multiple  name="playbook_server" id="playbook_server" class="form-control">
                                            	{% for ds in serverList %}
                                            			{% if ds.count == 1 %}
                                            				<option name="playbook_server" value="{{ds.id}}" selected="selected">{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
                                            			{% else %}
                                            				<option name="playbook_server" value="{{ds.id}}" >{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
                                            			{% endif %}
                                            	{% endfor %}
                                            </select>
                                        </div>                                          
                                        <div class="form-group">
                                            <label>用户组<i class="fa fa-info-circle" data-toggle="tooltip"  title="授权给那些用户组能够使用"></i></label>
                                            <select class="form-control" name="playbook_auth_group">
                                            	<option name="playbook_auth_group" value="0">选择用户组</option>
                                            	{% for ds in groupList %}
                                            		{% if ds.id == playbook.playbook_auth_group %}
                                            			<option name="playbook_auth_group" value="{{ds.id}}" selected="selected">{{ds.name}}</option>
                                            		{% else %}
                                            			<option name="playbook_auth_group" value="{{ds.id}}">{{ds.name}}</option>
                                            		{% endif %}
                                            		
                                            	{% endfor %}
                                            </select>
                                        </div>                                                                              
                                        <div class="form-group">
                                            <label>用户<i class="fa fa-info-circle" data-toggle="tooltip"  title="授权给那些用户能够使用"></i></label>
                                            <select class="form-control" name="playbook_auth_user">
                                            	<option name="playbook_auth_user" value="0">选择用户</option>
                                            	{% for ds in userList %}
                                            		{% if ds.id == playbook.playbook_auth_user %}
                                            			<option name="playbook_auth_user" value="{{ds.id}}" selected="selected">{{ds.username}}</option>
                                            		{% else %}
                                            			<option name="playbook_auth_user" value="{{ds.id}}">{{ds.username}}</option>
                                            		{% endif %}
                                            	{% endfor %}
                                            </select>
                                        </div>  
                                        <div class="form-group">
                                            <label>剧本外部变量<i class="fa fa-info-circle" data-toggle="tooltip"  title="值为json格式"></i></label>
                                            <textarea class="form-control" rows="10" name="playbook_vars" id="playbook_vars">{{playbook.playbook_vars}}</textarea>
                                            <p class="help-block">
												例如：{"host":["192.168.1.31","192.168.1.233"],"user":"root"}
                                            </p>
                                        </div>                                        
                                </div>
                                <!-- /.col-lg-6 (nested) -->
                               </form> 
                            </div>
                            <!-- /.row (nested) -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
</div>
    <!-- ACE Editor -->   
	<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
	<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
	<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
	<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<script type="text/javascript">
$(function () { $("[data-toggle='tooltip']").tooltip(); });

function oBtInventorySelect(obj){
	   var obj = document.getElementById("ansible_inventory"); 
	   var index = obj.selectedIndex;
	   var sId = obj.options[index].value; 
	   if ( sId  > 0){	 
			$.ajax({
				dataType: "JSON",
				url: "/api/inventory/" + sId +"/", //请求地址
				type:"GET",  //提交类似
				success:function(response){
					if ( JSON.stringify(response["data"]) != '{}'){
						$.notify({
							title: "<strong>发现资产:</strong>",
							message:  "<pre>" + JSON.stringify(response["data"],null,4) + "</pre>"
						},
						{
							type: 'success'
						});	
					}
					else {
						$.notify({
							title: "<strong>Ops：</strong>",
							message: "该条件下未发现资产~"
						},
						{
							type: 'danger'
						});
					}
				
						
				},
			});	
	   }
}

function oBtServiceSelect(model,ids){
	   var obj = document.getElementById(ids); 
	   var index = obj.selectedIndex;
	   var sId = obj.options[index].value; 
	   if ( sId  > 0){	 
			$.ajax({
				dataType: "JSON",
				url:'/assets_server/', //请求地址
				type:"POST",  //提交类似
				data:{
					"query":model,
					"id":sId
				},
				success:function(response){
					var sHtml = '';
					for (var i=0; i <response["data"].length; i++){
						sHtml += '<br>' + response["data"][i]["ip"]  
					};  
					if ( sHtml.length > 0){
						$.notify({
							title: "<strong>发现主机:</strong>",
							message: sHtml
						},
						{
							type: 'info'
						});	
						$('#run_ansible_model').removeAttr("disabled");
					}
					else {
						$.notify({
							title: "<strong>Ops：</strong>",
							message: "该条件下未发现主机资源~"
						},
						{
							type: 'danger'
						});
						$('#run_ansible_model').attr("disabled",true);
					}
				
						
				},
			});	
	   }
	   else{
		   $('#server option:selected').empty();
		   $('#server').attr("disabled",true);
	   }

}


{% if playbook.playbook_type == 1 %}
	$(function () {
		var editor = ace.edit("compile-editor");
		require("ace/ext/old_ie");
		var langTools = ace.require("ace/ext/language_tools");
		editor.setTheme("ace/theme/monokai");
		editor.getSession().setMode("ace/mode/yaml");
		editor.setShowPrintMargin(false);
		editor.setOptions({
		    enableBasicAutocompletion: true,
		    enableSnippets: true,
		    enableLiveAutocompletion: true
		}); 
				 
	});
	
	
    function getMultiple(){
        var select = document.getElementById("playbook_server");
        var str = [];
        for(i=0;i<select.length;i++){
            if(select.options[i].selected){
                str.push(select[i].value);
            }
        }
        return str;
    } 	
	  
    
	function oBtAnsiblePlaybookOnline(obt) {
		var editor = ace.edit("compile-editor");
	    var contents = editor.getSession().getValue(); 
	    var playbook_name = document.getElementsByName("playbook_name")[0].value;
	    var server_model = $("#server_model").val();
	    var ansible_service = $("#ansible_service").val();
	    if (server_model=='service' && ansible_service.length == 0){
	    	window.wxc.xcConfirm("请选择一个业务类型", window.wxc.xcConfirm.typeEnum.error);
	    	return false;	    	
	    }
	    else if ( contents.length == 0 || playbook_name.length == 0 ){
	    	window.wxc.xcConfirm("剧本名称或者内容不能为空", window.wxc.xcConfirm.typeEnum.error);
	    	return false;
	    };
		$.ajax({
			  type: 'POST',
			  url: '/apps/playbook/online/modf/{{playbook.id}}/',
			  data: {
				  "playbook_name":playbook_name,
				  'server_model':document.getElementById("server_model").value,
				  "playbook_desc":document.getElementById("playbook_desc").value,
				  "playbook_vars":document.getElementsByName("playbook_auth_user")[0].value,
				  "playbook_server":getMultiple(),
				  "playbook_auth_group":document.getElementsByName("playbook_auth_group")[0].value,
				  'playbook_auth_user':document.getElementsByName("playbook_auth_user")[0].value,
				  'ansible_service':document.getElementsByName("ansible_service")[0].value,
				  'ansible_group':document.getElementsByName("ansible_group")[0].value,
				  'ansible_inventory':document.getElementsByName("ansible_inventory")[0].value,				  
				  "playbook_vars":document.getElementsByName("playbook_vars")[0].value,
				  "playbook_content":contents
			  },
		      success:function(response){	
	                if (response["code"]=="200"){ 
	                	window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
/* 	                	window.location.reload(); */
	                }
		        	else{
		        		window.wxc.xcConfirm("添加失败：" + response["msg"], window.wxc.xcConfirm.typeEnum.error);
		        	};	

				},
	          error:function(response){
	          	window.wxc.xcConfirm("添加失败", window.wxc.xcConfirm.typeEnum.error);
	          },							  
			});
	};		
{% endif %}
{% if playbook.playbook_vars %}
	var songResJson=JSON.parse(document.getElementById('playbook_vars').value);
	$("#playbook_vars").text(JSON.stringify(songResJson,null,2)); 
{% endif %}
{% if errorInfo %}
	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}


function oBtAnsibleServerl(){
	   var obj = document.getElementById("server_model"); 
	   var index = obj.selectedIndex;
	   var value = obj.options[index].value; 
	   if (value=="group"){
		   document.getElementById("group_server").style.display = "";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "none";
	   }
	   else if (value=="custom"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "";
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "none";
	   }
	   else if (value=="service"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "";
		   document.getElementById("inventory_server").style.display = "none";
	   }	
	   else if (value=="inventory"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "";
	   }		   
	   else {
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none"; 
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "none";
	   }	
}

function oBtProjectSelect(){
	   $('#ansible_service').removeAttr("disabled");
	   var obj = document.getElementById("ansible_project"); 
	   var index = obj.selectedIndex;
	   var projectId = obj.options[index].value; 
	   if ( projectId > 0){	 
			$.ajax({
				dataType: "JSON",
				url:'/api/project/'+ projectId + '/', //请求地址
				type:"GET",  //提交类似
				success:function(response){
					var binlogHtml = '<select class="form-control" name="ansible_service" id="ansible_service" onchange="javascript:oBtServiceSelect();" required><option selected="selected" name="ansible_service" value="">请选择业务类型</option>'
					var selectHtml = '';
					for (var i=0; i <response["service_assets"].length; i++){
						 selectHtml += '<option name="ansible_service" value="'+ response["service_assets"][i]["id"] +'">' + response["service_assets"][i]["service_name"] + '</option>' 
					};                        
					binlogHtml =  binlogHtml + selectHtml + '</select>';
					document.getElementById("ansible_service").innerHTML= binlogHtml;	
						
				},
			});	
	   }
	   else{
		   $('#ansible_service').attr("disabled",true);
	   }

}

</script>

{% endblock %}